package com.zhangxi.handle;

/**
 * @author zhangxi
 * @create 2024-04-18 11:35
 */

import com.zhangxi.constant.MessageConstant;
import com.zhangxi.exception.BaseException;
import com.zhangxi.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 异常处理类
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandle(BaseException e) {
        log.error("异常信息：{}", e.getMessage());
        return Result.error(e.getMessage());
    }

    /**
     * 处理新增用户用户被占用异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandle(SQLIntegrityConstraintViolationException ex) {
//        Duplicate entry '测试用户2' for key 'employee.idx_username'
        String message = ex.getMessage();
        //判断异常信息中是否包含Duplicate entry
        if (message.contains("Duplicate entry")){
            //根据空格切割异常信息放入数组中
            String[] split = message.split(" ");
            String username =split[2];
            String msg  = username + MessageConstant.ALREADY_EXISTS;
            return Result.error(msg);
        }else {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
    }

}
